package com.github.caijh.mall.store.service.impl;


import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson.JSON;
import com.github.caijh.commons.util.DateUtils;
import com.github.caijh.framework.data.redis.Redis;
import com.github.caijh.framework.log.util.LogUtils;
import com.github.caijh.mall.constants.Constants;
import com.github.caijh.mall.store.model.StoreOrder;
import com.github.caijh.mall.store.service.OrderTaskService;
import com.github.caijh.mall.store.service.StoreOrderService;
import com.github.caijh.mall.store.service.StoreOrderTaskService;
import com.github.caijh.mall.store.utilService.OrderUtils;
import com.github.caijh.mall.wechat.service.impl.WechatSendMessageForMinService;
import com.github.caijh.mall.wechat.vo.WechatSendMessageForGetPackage;
import com.github.caijh.mall.wechat.vo.WechatSendMessageForOrderCancel;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderTaskServiceImpl implements OrderTaskService {

    private static final Logger logger = LogUtils.getLogger(OrderTaskServiceImpl.class);

    @Autowired
    private Redis redis;

    @Autowired
    private StoreOrderTaskService storeOrderTaskService;

    @Autowired
    private StoreOrderService storeOrderService;

    @Autowired
    private WechatSendMessageForMinService wechatSendMessageForMinService;

    @Autowired
    private OrderUtils orderUtils;

    /**
     * 用户取消订单
     *
     * @author Mr.Zhang
     * @since 2020-07-09
     */
    @Override
    public void cancelByUser() {
        String redisKey = Constants.ORDER_TASK_REDIS_KEY_AFTER_CANCEL_BY_USER;
        Long size = redis.getRedisTemplate().opsForList().size(redisKey);
        logger.info("OrderTaskServiceImpl.cancelByUser | size:" + size);
        if (size < 1) {
            return;
        }
        for (int i = 0; i < size; i++) {
            //如果10秒钟拿不到一个数据，那么退出循环
            Object data = redis.getRedisTemplate().opsForList().rightPop(redisKey, 10L, TimeUnit.SECONDS);
            if (null == data) {
                continue;
            }
            try {
                StoreOrder storeOrder = storeOrderService.getById(Integer.valueOf(data.toString()));
                boolean result = storeOrderTaskService.cancelByUser(storeOrder);
                if (!result) {
                    redis.getRedisTemplate().opsForList().leftPush(redisKey, data);
                } else {
                    WechatSendMessageForOrderCancel orderCancel = new WechatSendMessageForOrderCancel(
                            "暂无", DateUtils.nowAsString(), "", "暂无", orderUtils.getPayTypeStrByOrder(storeOrder),
                            orderUtils.getStoreNameAndCarNumString(storeOrder.getId()), storeOrder.getOrderId(),
                            storeOrder.getStatus() + "", storeOrder.getPayPrice() + "", storeOrder.getCreateTime() + "",
                            "CRMEB", "暂无", storeOrder.getOrderId(), "CRMEB", "暂无"
                    );
                    wechatSendMessageForMinService.sendOrderCancelMessage(orderCancel, storeOrder.getUid());
                }
            } catch (Exception e) {
                redis.getRedisTemplate().opsForList().leftPush(redisKey, data);
            }
        }
    }

    private StoreOrder getJavaBeanStoreOrder(Object data) {
        return JSON.toJavaObject(JSON.parseObject(data.toString()), StoreOrder.class);
    }

    /**
     * 执行 用户退款申请
     *
     * @author Mr.Zhang
     * @since 2020-07-09
     */
    @Override
    public void refundApply() {
        String redisKey = Constants.ORDER_TASK_REDIS_KEY_AFTER_REFUND_BY_USER;
        Long size = redis.getRedisTemplate().opsForList().size(redisKey);
        logger.info("OrderTaskServiceImpl.refundApply | size:" + size);
        if (size < 1) {
            return;
        }
        for (int i = 0; i < size; i++) {
            //如果10秒钟拿不到一个数据，那么退出循环
            Object orderId = redis.getRedisTemplate().opsForList().rightPop(redisKey, 10L, TimeUnit.SECONDS);
            if (null == orderId) {
                continue;
            }
            try {
                StoreOrder storeOrder = storeOrderService.getById(Integer.valueOf(orderId.toString()));
                boolean result = storeOrderTaskService.refundApply(storeOrder);
                if (!result) {
                    redis.getRedisTemplate().opsForList().leftPush(redisKey, orderId);
                }
            } catch (Exception e) {
                redis.getRedisTemplate().opsForList().leftPush(redisKey, orderId);
            }
        }
    }

    /**
     * 完成订单
     *
     * @author Mr.Zhang
     * @since 2020-07-09
     */
    @Override
    public void complete() {
        String redisKey = Constants.ORDER_TASK_REDIS_KEY_AFTER_COMPLETE_BY_USER;
        Long size = redis.getRedisTemplate().opsForList().size(redisKey);
        logger.info("OrderTaskServiceImpl.complete | size {}", size);
        if (size < 1) {
            return;
        }
        for (int i = 0; i < size; i++) {
            //如果10秒钟拿不到一个数据，那么退出循环
            Object data = redis.getRedisTemplate().opsForList().rightPop(redisKey, 10L, TimeUnit.SECONDS);
            if (null == data) {
                continue;
            }
            try {
                StoreOrder storeOrder = getJavaBeanStoreOrder(data);
                boolean result = storeOrderTaskService.complete(storeOrder);
                if (!result) {
                    redis.getRedisTemplate().opsForList().leftPush(redisKey, data);
                }
            } catch (Exception e) {
                redis.getRedisTemplate().opsForList().leftPush(redisKey, data);
            }
        }
    }

    /**
     * 用户已收货
     *
     * @author Mr.Zhang
     * @since 2020-07-09
     */
    @Override
    public void takeByUser() {
        String redisKey = Constants.ORDER_TASK_REDIS_KEY_AFTER_TAKE_BY_USER;
        Long size = redis.getRedisTemplate().opsForList().size(redisKey);
        logger.info("OrderTaskServiceImpl.takeByUser | size {}", size);
        if (size == null || size < 1) {
            return;
        }
        for (int i = 0; i < size; i++) {
            //如果10秒钟拿不到一个数据，那么退出循环
            Object id = redis.getRedisTemplate().opsForList().rightPop(redisKey, 10L, TimeUnit.SECONDS);
            if (null == id) {
                continue;
            }
            try {
                StoreOrder storeOrder = storeOrderService.getByEntityOne(new StoreOrder().setId(Integer.valueOf(id.toString())));
                boolean result = storeOrderTaskService.takeByUser(storeOrder);
                if (!result) {
                    redis.getRedisTemplate().opsForList().leftPush(redisKey, id);
                } else {
                    // 微信小程序订阅消息通知 确认收货
                    WechatSendMessageForGetPackage getPackage = new WechatSendMessageForGetPackage(
                            orderUtils.getPayTypeStrByOrder(storeOrder), orderUtils.getStoreNameAndCarNumString(storeOrder.getId()),
                            "CRMEB", storeOrder.getUserAddress(), DateUtils.nowAsString(), storeOrder.getOrderId()
                    );
                    wechatSendMessageForMinService.sendGetPackageMessage(getPackage, storeOrder.getUid());
                }
            } catch (Exception e) {
                redis.getRedisTemplate().opsForList().leftPush(redisKey, id);
            }
        }
    }

    /**
     * 用户删除订单
     *
     * @author Mr.Zhang
     * @since 2020-07-09
     */
    @Override
    public void deleteByUser() {
        String redisKey = Constants.ORDER_TASK_REDIS_KEY_AFTER_DELETE_BY_USER;
        Long size = redis.getRedisTemplate().opsForList().size(redisKey);
        logger.info("OrderTaskServiceImpl.deleteByUser | size {}", size);
        if (size == null || size < 1) {
            return;
        }
        for (int i = 0; i < size; i++) {
            //如果10秒钟拿不到一个数据，那么退出循环
            Object data = redis.getRedisTemplate().opsForList().rightPop(redisKey, 10L, TimeUnit.SECONDS);
            if (null == data) {
                continue;
            }
            try {
                StoreOrder storeOrder = getJavaBeanStoreOrder(data);
                boolean result = storeOrderTaskService.deleteByUser(storeOrder);
                if (!result) {
                    redis.getRedisTemplate().opsForList().leftPush(redisKey, data);
                }
            } catch (Exception e) {
                redis.getRedisTemplate().opsForList().leftPush(redisKey, data);
            }
        }
    }

}
